// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/exec/container_row_serde.h>
#include <pollux/expression/function_signature.h>
#include <pollux/functions/prestosql/aggregates/aggregate_names.h>
#include <pollux/functions/prestosql/aggregates/map_accumulator.h>

namespace kumo::pollux::aggregate::prestosql {
    template<typename K, typename AccumulatorType>
    class MapAggregateBase : public exec::Aggregate {
    public:
        explicit MapAggregateBase(TypePtr resultType) : Aggregate(resultType) {
        }

        int32_t accumulatorFixedWidthSize() const override {
            return sizeof(AccumulatorType);
        }

        bool isFixedSize() const override {
            return false;
        }

        void extractValues(char **groups, int32_t numGroups, VectorPtr *result)
        override {
            auto map_vector = (*result)->as<MapVector>();
            POLLUX_CHECK(map_vector);
            map_vector->resize(numGroups);
            auto mapKeys = map_vector->mapKeys();
            auto mapValues = map_vector->mapValues();
            auto numElements = countElements(groups, numGroups);
            mapKeys->resize(numElements);
            mapValues->resize(numElements);

            auto *rawNulls = getRawNulls(map_vector);
            vector_size_t offset = 0;

            for (int32_t i = 0; i < numGroups; ++i) {
                char *group = groups[i];

                if (isNull(group)) {
                    map_vector->set_null(i, true);
                    map_vector->setOffsetAndSize(i, 0, 0);
                    continue;
                }

                clearNull(rawNulls, i);

                auto accumulator = value<AccumulatorType>(group);
                auto mapSize = accumulator->size();
                if (mapSize) {
                    accumulator->extract(mapKeys, mapValues, offset);
                    map_vector->setOffsetAndSize(i, offset, mapSize);
                    offset += mapSize;
                } else {
                    map_vector->setOffsetAndSize(i, 0, 0);
                }
            }
        }

        void extractAccumulators(char **groups, int32_t numGroups, VectorPtr *result)
        override {
            extractValues(groups, numGroups, result);
        }

        void addIntermediateResults(
            char **groups,
            const SelectivityVector &rows,
            const std::vector<VectorPtr> &args,
            bool /*mayPushdown*/) override {
            addMapInputToAccumulator(groups, rows, args, false);
        }

        void addSingleGroupIntermediateResults(
            char *group,
            const SelectivityVector &rows,
            const std::vector<VectorPtr> &args,
            bool /*mayPushdown*/) override {
            addSingleGroupMapInputToAccumulator(group, rows, args, false);
        }

    protected:
        vector_size_t countElements(char **groups, int32_t numGroups) const {
            vector_size_t size = 0;
            for (int32_t i = 0; i < numGroups; ++i) {
                size += value<AccumulatorType>(groups[i])->size();
            }
            return size;
        }

        void destroyInternal(melon::Range<char **> groups) override {
            for (auto group: groups) {
                if (isInitialized(group)) {
                    auto accumulator = value<AccumulatorType>(group);
                    accumulator->free(*allocator_);
                }
            }
        }

        AccumulatorType *accumulator(char *group) {
            return value<AccumulatorType>(group);
        }

        static void checkNullKeys(
            const DecodedVector &keys,
            vector_size_t offset,
            vector_size_t size) {
            static const char *kNullKey = "map key cannot be null";
            if (keys.may_have_nulls()) {
                for (auto i = offset; i < offset + size; ++i) {
                    POLLUX_USER_CHECK(!keys.is_null_at(i), kNullKey);
                }
            }
        }

        void addMapInputToAccumulator(
            char **groups,
            const SelectivityVector &rows,
            const std::vector<VectorPtr> &args,
            bool /*mayPushdown*/) {
            decodedMaps_.decode(*args[0], rows);
            auto map_vector = decodedMaps_.base()->template as<MapVector>();

            decodedKeys_.decode(*map_vector->mapKeys());
            decodedValues_.decode(*map_vector->mapValues());

            POLLUX_CHECK_NOT_NULL(map_vector);
            rows.applyToSelected([&](vector_size_t row) {
                auto group = groups[row];
                auto accumulator = value<AccumulatorType>(group);

                if (!decodedMaps_.is_null_at(row)) {
                    clearNull(group);
                    auto decodedRow = decodedMaps_.index(row);
                    auto offset = map_vector->offsetAt(decodedRow);
                    auto size = map_vector->sizeAt(decodedRow);
                    auto tracker = trackRowSize(group);
                    checkNullKeys(decodedKeys_, offset, size);
                    for (auto i = offset; i < offset + size; ++i) {
                        accumulator->insert(decodedKeys_, decodedValues_, i, *allocator_);
                    }
                }
            });
        }

        void addSingleGroupMapInputToAccumulator(
            char *group,
            const SelectivityVector &rows,
            const std::vector<VectorPtr> &args,
            bool /*mayPushdown*/) {
            decodedMaps_.decode(*args[0], rows);
            auto map_vector = decodedMaps_.base()->template as<MapVector>();

            decodedKeys_.decode(*map_vector->mapKeys());
            decodedValues_.decode(*map_vector->mapValues());

            auto accumulator = value<AccumulatorType>(group);

            POLLUX_CHECK_NOT_NULL(map_vector);
            rows.applyToSelected([&](vector_size_t row) {
                if (!decodedMaps_.is_null_at(row)) {
                    clearNull(group);
                    auto decodedRow = decodedMaps_.index(row);
                    auto offset = map_vector->offsetAt(decodedRow);
                    auto size = map_vector->sizeAt(decodedRow);
                    checkNullKeys(decodedKeys_, offset, size);
                    for (auto i = offset; i < offset + size; ++i) {
                        accumulator->insert(decodedKeys_, decodedValues_, i, *allocator_);
                    }
                }
            });
        }

        void initializeNewGroupsInternal(
            char **groups,
            melon::Range<const vector_size_t *> indices) override {
            const auto &type = resultType()->childAt(0);
            for (auto index: indices) {
                new(groups[index] + offset_) AccumulatorType(type, allocator_);
            }
            setAllNulls(groups, indices);
        }

        DecodedVector decodedKeys_;
        DecodedVector decodedValues_;
        DecodedVector decodedMaps_;
    };

    template<template <typename K, typename Accumulator = MapAccumulator<K>>
        class TAggregate>
    std::unique_ptr<exec::Aggregate> createMapAggregate(const TypePtr &resultType) {
        auto typeKind = resultType->childAt(0)->kind();
        switch (typeKind) {
            case TypeKind::BOOLEAN:
                return std::make_unique<TAggregate<bool> >(resultType);
            case TypeKind::TINYINT:
                return std::make_unique<TAggregate<int8_t> >(resultType);
            case TypeKind::SMALLINT:
                return std::make_unique<TAggregate<int16_t> >(resultType);
            case TypeKind::INTEGER:
                return std::make_unique<TAggregate<int32_t> >(resultType);
            case TypeKind::BIGINT:
                return std::make_unique<TAggregate<int64_t> >(resultType);
            case TypeKind::REAL:
                return std::make_unique<TAggregate<float> >(resultType);
            case TypeKind::DOUBLE:
                return std::make_unique<TAggregate<double> >(resultType);
            case TypeKind::TIMESTAMP:
                return std::make_unique<TAggregate<Timestamp> >(resultType);
            case TypeKind::VARBINARY:
                [[fallthrough]];
            case TypeKind::VARCHAR:
                return std::make_unique<TAggregate<StringView> >(resultType);
            case TypeKind::ARRAY:
            case TypeKind::MAP:
            case TypeKind::ROW:
                return std::make_unique<TAggregate<ComplexType> >(resultType);
            case TypeKind::UNKNOWN:
                return std::make_unique<TAggregate<int32_t> >(resultType);
            default:
                POLLUX_UNREACHABLE("Unexpected type {}", mapTypeKindToName(typeKind));
        }
    }
} // namespace kumo::pollux::aggregate::prestosql
